package cxydmmszl.chapter01.t001;

import java.util.Stack;

/**
 * @author habitplus
 * @since 2021-08-04 21:06
 */
public class MyStack02 {
    private final Stack<Integer> dataStack = new Stack<>();
    private final Stack<Integer> minStack = new Stack<>();


    /**
     * 入栈：每次入栈时，都与之前的最小值进行判断，
     *      若 <= ，则当前数压入 minStack，否则不压入
     */
    public void push(int num) {
        if (dataStack.isEmpty()) {
            minStack.push(num);
        } else {
            if (minStack.peek() >= num)
                minStack.push(num);
        }
        dataStack.push(num);
    }

    /**
     * 出栈：当前要出栈的数与 minStack 的栈顶元素相等，minStack 也要出栈，否则不出栈
     */
    public int pop() {
        ensureNonEmpty();
        int top = dataStack.pop();
        if (top == minStack.peek()) {
            minStack.pop();
        }
        return top;
    }

    /**
     * getMin 函数
     */
    public int getMin() {
        ensureNonEmpty();
        return minStack.peek();
    }

    private void ensureNonEmpty() {
        if (dataStack.isEmpty())
            throw new RuntimeException("The stack is empty!");
    }

    /**
     * 返回栈顶元素
     */
    public int peek() {
        ensureNonEmpty();
        return dataStack.peek();
    }
}
